package org.rbac.util;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.dom4j.Element;
import org.rbac.content.configure.RbacConfigure;
import org.rbac.content.define.RbacKeyDefine.keys;

import com.kingschan.easyquery.vo.SqlCommand;
import com.kingschan.lang.BeanUtil;
import com.kingschan.sqlparser.DbType;
/**
 * 
*  <pre>    
* 类名称：SqlCmdUtil 
* 类描述：   sqlcommand实体工具类
* 创建人：陈国祥   (kingschan)
* 创建时间：2014-8-1 上午11:41:01   
* 修改人：Administrator   
* 修改时间：2014-8-1 上午11:41:01   
* 修改备注：   
* @version V1.0
* </pre>
 */
public class SqlCmdUtil {
    private static Logger log = Logger.getLogger(SqlCmdUtil.class);
        
    public  SqlCommand getSqlCmdById(String id,HttpServletRequest req){
        SqlCommand cmd = null;
        String path = String.format("%s/cache/%s.data", RbacConfigure.getInstance().get(keys.WEB_INF),id);
        try {
            cmd = (SqlCommand) BeanUtil.DesSerializationObject(path);
        } catch (Exception e) {
            e.printStackTrace();            
        }
        return cmd;
    }
	/**
	 * 通过xml定义的id得到sqlcommand对象
	 * @param id xml id名字
	 * @return
	 * @throws Exception 
	 * @throws  
	 */
	public  SqlCommand getSqlCmdById(String fileName,String id){
		SqlCommand cmd = null;
		String path=String.format("%s/sql/oracle/%s.xml",RbacConfigure.getInstance().get(keys.WEB_INF),fileName).replace("/", File.separator);
//		System.out.println("SQl路径："+path);
//		log.debug("get sqlcommand xml file path:"+path);
//		Properties prop = System.getProperties(); 
//        String os = prop.getProperty("os.name");
//        log.debug("操作系统："+os);
//        if (os.toUpperCase().startsWith("WIN")) {
//            path=path.replace("/", File.separator);
//        }
//        }else if (os.toUpperCase().contains("LINUX")) {
//            path=path.replace("/", File.separator);
//        }
        File f = new File(path);
        try {
            if (f.exists()) {
                cmd=new SqlCommand();
                XmlOperation xml = new XmlOperation(f);
                Element node= (Element) xml.getNodeByExpression(String.format("//sql[@id='%s']", id));
               // cmd.setJdbcConnection(node.attributeValue("jdbc"));
                cmd.setDBtype(DbType.valueOf(node.attributeValue("dbtype").toUpperCase()));
                cmd.setSql(node.getTextTrim());
               
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e);
        }
        return cmd;
	}
	
	
}
